package com.dk.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import java.io.ByteArrayOutputStream;
import java.security.*;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

/**
 * RSA 非对称加密工具类
 */
public class RsaSecretKey {
	public static final String KEY_ALGORITHM = "RSA";//加密方式
	private static final String PUBLIC_KEY = "RSAPublicKey";//生成公钥的key
	private static final String PRIVATE_KEY = "RSAPrivateKey";//生成私钥的key
	public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
	/**
	 * RSA最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/**
	 * RSA最大解密密文大小
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;

	// 获得公钥字符串
	public static String getPublicKeyStr(Map<String, Object> keyMap) throws Exception {
		// 获得map中的公钥对象 转为key对象
		Key key = (Key) keyMap.get(PUBLIC_KEY);
		// 编码返回字符串
		return encryptBASE64(key.getEncoded());
	}

	// 获得私钥字符串
	public static String getPrivateKeyStr(Map<String, Object> keyMap) throws Exception {
		// 获得map中的私钥对象 转为key对象
		Key key = (Key) keyMap.get(PRIVATE_KEY);
		// 编码返回字符串
		return encryptBASE64(key.getEncoded());
	}

	// 获取公钥
	public static PublicKey getPublicKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey publicKey = keyFactory.generatePublic(keySpec);
		return publicKey;
	}

	// 获取私钥
	public static PrivateKey getPrivateKey(String key) throws Exception {
		byte[] keyBytes;
		keyBytes = (new BASE64Decoder()).decodeBuffer(key);
		PKCS8EncodedKeySpec keySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateKey = keyFactory.generatePrivate(keySpec);
		return privateKey;
	}

	// 解码返回byte
	public static byte[] decryptBASE64(String key) throws Exception {
		return (new BASE64Decoder()).decodeBuffer(key);
	}

	// 编码返回字符串
	public static String encryptBASE64(byte[] key) throws Exception {
		return (new BASE64Encoder()).encodeBuffer(key);
	}

	// ***************************签名和验证*******************************
	public static byte[] sign(byte[] data, String privateKeyStr) throws Exception {
		PrivateKey priK = getPrivateKey(privateKeyStr);
		Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
		sig.initSign(priK);
		sig.update(data);
		return sig.sign();
	}

	public static boolean verify(byte[] data, byte[] sign, String publicKeyStr) throws Exception {
		PublicKey pubK = getPublicKey(publicKeyStr);
		Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
		sig.initVerify(pubK);
		sig.update(data);
		return sig.verify(sign);
	}

	//初始化生成公钥私钥的方式及公钥使用key/私钥使用的key
	public static Map<String, Object> initKey() throws Exception {
		KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance(KEY_ALGORITHM);
		keyPairGen.initialize(1024);
		KeyPair keyPair = keyPairGen.generateKeyPair();
		RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();
		RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
		Map<String, Object> keyMap = new HashMap<>(2);
		keyMap.put(PUBLIC_KEY, publicKey);
		keyMap.put(PRIVATE_KEY, privateKey);
		return keyMap;
	}

	// ************************加密解密**************************
	public static byte[] encrypt(byte[] plainText, String publicKeyStr) throws Exception {
		PublicKey publicKey = getPublicKey(publicKeyStr);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.ENCRYPT_MODE, publicKey);
		int inputLen = plainText.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		int i = 0;
		byte[] cache;
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(plainText, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(plainText, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptText = out.toByteArray();
		out.close();
		return encryptText;
	}

	public static byte[] decrypt(byte[] encryptText, String privateKeyStr) throws Exception {
		PrivateKey privateKey = getPrivateKey(privateKeyStr);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM);
		cipher.init(Cipher.DECRYPT_MODE, privateKey);
		int inputLen = encryptText.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptText, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptText, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] plainText = out.toByteArray();
		out.close();
		return plainText;
	}

	public static void main(String[] args) {
		Map<String, Object> keyMap;
		try {
			keyMap = initKey();
			String publicKey = getPublicKeyStr(keyMap);
			System.out.println("公钥------------------");
			System.out.println(publicKey);
			String privateKey = getPrivateKeyStr(keyMap);
			System.out.println("私钥------------------");
			System.out.println(privateKey);
			
			String privateStr = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKKu5QYBftQmaI16uNhn34iaCbDm\r\n" + 
					"eO9Tt9VUB7QpskHSlov8f7KUBuRmdaUDDuEWPe0Q6kJgEhE9dRGR692LqfaUNZ2SN+AYqGNa67U1\r\n" + 
					"HIgqM3sTlP8RX2P/ikp5oZkqsQgBuuxWjibcfL1ECQ/Qm54zG77OWMaj15OCMl8fubGBAgMBAAEC\r\n" + 
					"gYAVvNLjY43D4UH1LaHHYNHQmeyTk6gzKneU7L5+x1eHThFJsTqK7RairEIqA2eYkfVCWRFEPzwK\r\n" + 
					"y7B54YqntsLF9jr9rFupmqQPJQWyeFKWOMbW0Wu51agTqYtjKicjVPxLqw8/OWQ6LxA5qCahtOWY\r\n" + 
					"S0elLKufgu36zsIMhLSAAQJBAN3xcp8cR994jnYgbUilj5Zk2+6WGkvaK3Cwr54TE8hS0oPD0Or2\r\n" + 
					"HB55IIc6iDjJ4BhQ/AKaAEURaClPX1EXdoECQQC7pYxYp/JuDSMt6Y1/3BMcaig2yHtuYI1vRq8/\r\n" + 
					"PCfGLtTGwoHdrhi8mVOVa6LSzeDPDJUBr/ovfR8xkk5WErsBAkAqhXO8YCK1AdfpcdT+MhoMak5o\r\n" + 
					"q4FmPupLsM40rtr/aj7C1+VS3swMWpCM1/35Q1QX1Iwzw2WB1g/qujY8xw4BAkEAgHpxBaK4UrGc\r\n" + 
					"DKuEvq6oRyRINHpASOrC7BWxl9JQSVl3Rj+XO3kgZsF0gTIZYcykyB8NRwJ+glVhLkfGaxiYAQJB\r\n" + 
					"ANyeW1CpdoTl4xFUqJLMLo2qspnnUWjH8q70Ry4En8BdYekGgXjcrAusQCg11w1c2667WtUSNNJd\r\n" + 
					"vxz65oqsLaM=";
			
			String publicStr = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCiruUGAX7UJmiNerjYZ9+Imgmw5njvU7fVVAe0\r\n" + 
					"KbJB0paL/H+ylAbkZnWlAw7hFj3tEOpCYBIRPXURkevdi6n2lDWdkjfgGKhjWuu1NRyIKjN7E5T/\r\n" + 
					"EV9j/4pKeaGZKrEIAbrsVo4m3Hy9RAkP0JueMxu+zljGo9eTgjJfH7mxgQIDAQAB";
			//加密
			byte[] bs = encrypt("abc".getBytes(),publicStr);
			System.out.println(new String(bs));
			//解密
			byte[] bs2 = decrypt(bs, privateStr);
			System.out.println(new String(bs2));
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
